import React, {
	Component
} from 'react';
import {
	observable,
	action,
	computed,
} from 'mobx';
import {
	Tools,
	Bubble,
	Toast,
	Icon,
	ListView,
	ActionSheet,
} from "weaver-mobile";
import {
	RouteLayout,
	SearchAdvanced,
} from 'weaver-mobile-page';
import moment from 'moment';
import {
	isEmpty,
	cloneDeep,
} from 'lodash';
import * as api from '../../apis/myAttendance.js';
import {getAutoEMSet, saveAutoEMSet} from '../../apis/sign.js';
import {
	forwardViewForm
} from '../../../workflowForm/util/forwardPage';
const getLabel = Tools.getLabel;

const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let wrapProps;
if (isIPhone) {
	wrapProps = {
		onTouchStart: e => e.preventDefault(),
	};
}

class MyAttendanceCopyStore {
	typeColors = {
		NORMAL: {
			type: 'check-circle-o',
			color: '#2db7f5'
		},
		BELATE: {
			type: 'blog-chidao',
			color: '#ff8f00'
		},
		LEAVEEARLY: {
			type: 'leave-early',
			color: '#7326ff'
		},
		ABSENT: {
			type: 'cross-circle',
			color: '#fc4b6c'
		},
		NOSIGN: {
			type: 'missed-signature-1',
			color: '#bd10e0'
		},
		LEAVE: {
			type: 'ask-for-leave',
			color: '#2db7f5'
		},
		EVECTION: {
			type: 'on-a-business-trip-1',
			color: '#30be3a'
		},
		OUTDAYS: {
			type: 'public-affairs',
			color: '#4f8cff'
		},
		OVERTIME: {
			type: 'overtime-1',
			color: '#8d6bf3'
		}
	};

	@observable isInit = false;
	@observable date = moment().format("YYYY-MM");

	@observable total = [];
	@observable detail = [];
	@observable abnormal = [];
	@observable leaveInfo = [];
	@observable calenderInfo = {};
	@observable signInfo = [];
	@observable kqDetailInfo = [];
	@observable balance = [];
	@observable leaveWorkflowInfo = [];

	@observable absence = {
		absenceDay: '',
		types: [],
		details: [],
	};

	@observable popoverVisible = false;
	@observable alllevel = '0';
	@observable subordinateDataSource = [];
	@observable searchBarValue = '';
	@observable hrmId = '';
	@observable selectedTab = "firstTab";
	@observable isLoadAllDatas = false;
	@observable serialInfo = "";
	@observable signWorkflowInfo = [];
	@observable isOnlyAttendance = false;

	@computed get absenceProLayout() {
		return new RouteLayout.Store({
			route: (!this.isSubordinate) ? '/sign' : '/subAttendanceCopy',
			id: 'absencePro'
		});
	}
	@computed get calenderLayout() {
		return new RouteLayout.Store({
			route: (!this.isSubordinate) ? '/sign' : '/subAttendanceCopy',
			id: 'calender'
		});
	}
	@computed get kqDetailLayout() {
		return new RouteLayout.Store({
			route: (!this.isSubordinate) ? '/sign' : '/subAttendanceCopy',
			id: 'kqDetail'
		});
	}
	@computed get absenceLayout() {
		return new RouteLayout.Store({
			route: (!this.isSubordinate) ? '/sign' : '/subAttendanceCopy',
			id: 'absence'
		});
	}
	@computed get overtimeLayout() {
		return new RouteLayout.Store({
			route: (!this.isSubordinate) ? '/sign' : '/subAttendanceCopy',
			id: 'overtime'
		});
	}
	@computed get balanceLayout() {
		return new RouteLayout.Store({
			route: (!this.isSubordinate) ? '/sign' : '/subAttendanceCopy',
			id: 'balance'
		});
	}
	@computed get leaveWorkflowLayout() {
		return new RouteLayout.Store({
			route: (!this.isSubordinate) ? '/sign' : '/subAttendanceCopy',
			id: 'leaveWorkflowInfo'
		});
	}

	@observable kqDetailSearch = new SearchAdvanced.Store({
		route: '/sign/kqDetail',
		id: 'kqDetailSearch',
	});

	@observable overtimeSearch = new SearchAdvanced.Store({
		route: '/sign/overtime',
		id: 'kqDetailSearch',
	});

	@observable subKqDetailSearch = new SearchAdvanced.Store({
		route: '/subAttendanceCopy/kqDetail',
		id: 'kqDetailSearch',
	});

	@observable subOvertimeSearch = new SearchAdvanced.Store({
		route: '/subAttendanceCopy/overtime',
		id: 'kqDetailSearch',
	});

	@observable subordinateSearch = new SearchAdvanced.Store({
		route: '/sign/kqDetail',
		id: 'subordinateSearch',
	});


	@observable chartOptions = {
		tooltip: {
			trigger: 'item',
			formatter: "{a} <br/>{b}: {c} ({d}%)",
			position: 'right',
		},
		series: [{
			type: 'pie',
			name: getLabel('16732', "出勤统计"),
			radius: ['90%', '75%'],
			avoidLabelOverlap: false,
			label: {
				normal: {
					show: true,
					position: 'center',
					rich: {
						a: {
							color: '#484A4D',
							fontSize: 24,
							lineHeight: 24
						},
						b: {
							color: '#666',
							fontSize: 11,
						},
					},
				}
			},
			color: ['#FF60AB', '#48A6FF'],
			data: []
		}]
	};

	@computed get dateExtra() {
		const extra = {};

		Object.values(this.calenderInfo).forEach(info => {
			const {
				date,
				isWorkDay,
				types,
				tip,
			} = info;

			Object.assign(extra, {
				[date]: isEmpty(types) ? {
					info: false,
					sign: isWorkDay ? '班' : (tip && {
						text: tip,
						color: 'green'
					})
				} : {
					info: false,
					sign: {
						text: <Icon {...this.typeColors[types[0]]} size="xxs" />
					}
				}
			});
		});

		return extra;

	}

	@computed get isSubordinate() {
		return this.hrmId;
	}

	@computed get defaultDate() {
		return this.getCalenderDate(this.date);
	}

	//date数据格式为：YYYY-MM
	getCalenderDate = (date) => {
		//本月取今日，其他月份取1号
		let signDate = moment().format("YYYY-MM-DD");

		const nowDate = moment().format("YYYY-MM");

		if (!moment(date).isSame(nowDate)) {
			signDate = `${date}-01`
		}
		return signDate;
	}

	init = () => {
		this.resetMyattendanceDatas();

		this.loadMyAttendanceInfo();
	}

	loadMyAttendanceInfo = () => {
		this.showToast();

		this.getHrmKQReportInfo().then(() => {
			this.hideToast();
			this.isInit = true;
		});
	}

	getHrmKQReportInfo = () => {
		return new Promise((resolve, reject) => {
			const params = {
				loaddata: '1',
				type: '2',
				typevalue: this.date
			};

			if (this.hrmId) {
				Object.assign(params, {
					resourceId: this.hrmId
				});
			}

			api.getHrmKQReportInfo(params).then(datas => {
				const {
					status,
					groupitem1,
					groupitem2,
					groupitem3,
					groupitem4,
					groupitem5,
					message,
					title,
				} = datas;

				if (status === '1') {
					this.total = groupitem1 && groupitem1.items;
					this.detail = groupitem3 && groupitem3.items;
					this.abnormal = groupitem2 && groupitem2.items;
					this.leaveInfo = groupitem5 && groupitem5.items;
					this.balance = groupitem4 && groupitem4.items;

					this.processChartOptions(groupitem1);

					if (title) {
						this.mainTitle = title; //查看明细返回后，需要使用该值来修改顶部bar中的标题。
						this.changeTitle(title);
					}

					resolve();
				} else {
					Bubble.error(message);
					reject();
				}
			})
		})
	}

	clipChartName = (name) => {
		if (window.e9_locale.userLanguage === 8) {
			return name.split("(")[0]
		}else{
			return name;
		}
		
	}

	processChartOptions = (groupitem1) => {
		const {
			name,
			value,
			items
		} = groupitem1;

		let total = 0;

		items.forEach((item) => {
			item.value = parseFloat(item.value);
			total += parseFloat(item.value);
		})

		this.chartOptions.series[0].label.normal.formatter = [
			`{a|${parseFloat(value)}}`,
			`{b|${this.clipChartName(name)}}`
		].join('\n');

		this.chartOptions.series[0].data = items;

		const chartSeries = this.chartOptions.series[0];

		if (total === 0) {
			chartSeries.color = ["#c5c5c5", "#c5c5c5"];
		} else {
			chartSeries.color = ['#FF60AB', '#48A6FF'];
		}
	}

	@action getAbsenceProInfo = () => {
		return new Promise((resolve, reject) => {
			const params = {
				type: '2',
				typevalue: this.date,
				kqtype: "leaveDays",
			};

			if (this.hrmId) {
				Object.assign(params, {
					resourceId: this.hrmId
				})
			}

			api.getHrmKQReportDetialInfo(params).then(datas => {
				const {
					api_status,
					message,
					title,
				} = datas;
				if (api_status) {
					Object.keys(this.absence).forEach(key => {
						if (datas[key]) {
							Object.assign(this.absence, {
								[key]: datas[key]
							})
						}
					});

					if (title) {
						this.changeTitle(title);
					}

					resolve();
				} else {
					Bubble.error(message);
					reject();
				}
			})
		})
	}

	@action getCalenderInfo = (date) => {
		return new Promise((resolve, reject) => {
			const params = {
				type: '2',
				loaddata: '1',
				typevalue: date ? date : this.date,
			}

			if (this.hrmId) {
				Object.assign(params, {
					resourceId: this.hrmId
				});
			}

			api.getHrmKQMonthReportInfo(params).then(datas => {
				const {
					status,
					result,
					message,
					title,
				} = datas;

				if (status === '1') {
					this.calenderInfo = result;
					if (title) {
						this.changeTitle(title);
					}
					resolve();
				} else {
					Bubble.error(message);
					reject();
				}
			})
		})
	}

	@action getSignInfo = (date) => {
		return new Promise((resolve, reject) => {
			const params = {
				isMobile: true,
				date,
			};

			if (this.hrmId) {
				Object.assign(params, {
					resourceId: this.hrmId
				});
			}
			api.getHrmKQSignInfo(params).then(datas => {
				const {
					api_status,
					data,
					workflowInfo
				} = datas, {
					signInfo,
					serialInfo,
				} = data;

				if (api_status) {
					if (signInfo) {
						this.signInfo = signInfo;
					}
					if (workflowInfo) {
						this.signWorkflowInfo = workflowInfo;
					}
					this.serialInfo = serialInfo;
					resolve();
				} else {
					Bubble.error(data.message);
					reject();
				}
			})
		})
	}

	@action loadLeaveWorkflowInfo = () => {
		this.showToast();

		this.leaveWorkflowInfo = [];

		const params = {
			searchDateselect: 6,
			searchDatefrom: `${this.date}-01`,
			searchDateto: `${this.date}-31`,
			kqtype: this.kqtype,
			type: 2,
		};

		if (this.hrmId) {
			Object.assign(params, {
				resourceId: this.hrmId
			});
		}

		this.getDetailList4Mobile(params, "workflow").then(() => {
			this.hideToast()
		})
	}

	@action getSubordinateCondition = () => {
		return new Promise((resolve, reject) => {
			this.subordinateSearch.getData({
				url: '/api/public/browser/condition/1',
				method: 'GET',
			}).then(datas => {
				resolve()
			}).catch(error => {
				Bubble.error(error);
				reject();
			});
		})
	}

	@action getDetailList4Mobile = (params, type) => {
		return new Promise((resolve, reject) => {
			api.getDetailList4Mobile(params).then(datas => {
				const {
					api_status,
					data,
					isEnd,
					message,
					title,
				} = datas;

				if (api_status) {
					if (data) {
						if (type === "workflow") {
							this.leaveWorkflowInfo = [...this.leaveWorkflowInfo, ...data];
						} else {
							this.kqDetailInfo = [...this.kqDetailInfo, ...data];
						}
					}
					if (title) {
						this.changeTitle(title);
						this.detailTitle = title;
					}

					this.isLoadAllDatas = (isEnd === undefined) ? true : isEnd;

					resolve();
				} else {
					Bubble.error(message);
					reject();
				}
			})
		})
	}

	renewSearchForm = () => {
		if (!this.isSubordinate) {
			this.kqDetailSearch = new SearchAdvanced.Store({
				route: '/sign/kqDetail',
				id: 'kqDetailSearch',
			});
			this.overtimeSearch = new SearchAdvanced.Store({
				route: '/sign/overtime',
				id: 'kqDetailSearch',
			});
		} else {
			this.subKqDetailSearch = new SearchAdvanced.Store({
				route: '/subAttendanceCopy/kqDetail',
				id: 'kqDetailSearch',
			});
			this.subOvertimeSearch = new SearchAdvanced.Store({
				route: '/subAttendanceCopy/overtime',
				id: 'kqDetailSearch',
			});
		}
	}

	getDetailCondition4Mobile = () => {
		this.showToast();
		return new Promise((resolve, reject) => {
			this.renewSearchForm();

			let search;
			if (!this.isSubordinate) {
				search = (this.kqtype === "OVERTIME") ? "overtimeSearch" : "kqDetailSearch";
			}else{
				search = (this.kqtype === "OVERTIME") ? "subOvertimeSearch" : "subKqDetailSearch";
			}

			this[search].responseKey = 'condition';
			const params = {
				url: '/api/kq/myattendance/getDetailCondition4Mobile',
				method: 'GET',
			};
			if (this.kqtype === "OVERTIME") {
				Object.assign(params, {
					params: {
						kqtype: "overtime"
					}
				});
			}
			this[search].getData(params).then(() => resolve()).catch(error => {
				Bubble.error(error);
				reject();
			});
		})
	}

	loadAbsenceProInfo = () => {
		this.showToast();
		this.getAbsenceProInfo().then(() => {
			this.hideToast();
		});
	}

	loadCalenderInfo = (date) => {
		let yearMonth = "",
			signDate = this.defaultDate;

		if (date) { //切换日历，date有值
			yearMonth = date[0].split("-").slice(0, 2).join("-");
			signDate = this.getCalenderDate(yearMonth);
		}

		this.showToast();
		this.getCalenderInfo(yearMonth).then(() => {
			this.getSignInfo(signDate).then(() => {
				this.hideToast();
			})
		});
	}

	loadKqDetailInfo = (datas) => {
		const {
			isScroll,
			type
		} = datas;

		this.showToast();

		if (!isScroll) {//滚动不能清空kqDetailInfo
			this.kqDetailInfo = [];
		}

		const params = {};

		if (type === "detail-with-search") {//页面带高级搜索
			let search;
			if (!this.isSubordinate) {
				search = (this.kqtype === "OVERTIME") ? "overtimeSearch" : "kqDetailSearch";
			}else{
				search = (this.kqtype === "OVERTIME") ? "subOvertimeSearch" : "subKqDetailSearch";
			};
			Object.assign(params, this.getAdvancedSearchFormParams(search));
		}

		Object.assign(params, {
			searchDateselect: 6,
			searchDatefrom: `${this.date}-01`,
			searchDateto: `${this.date}-31`,
			index: this.kqDetailInfo.length,
			pageSize: 100,
			kqtype: this.kqtype
		});

		if (this.hrmId) {
			Object.assign(params, {
				resourceId: this.hrmId
			});
		}

		this.getDetailList4Mobile(params).then(() => {
			this.hideToast();
		})

	}

	loadSubordinateInfo = () => {
		this.showToast();
		this.getSubordinateInfo().then(() => {
			this.hideToast();
		})
	}

	@action getSubordinateInfo = () => {
		return new Promise((resolve, reject) => {
			const params = {
				cmd: "branch",
				...this.getAdvancedSearchFormParams("subordinateSearch"),
			};

			if (this.alllevel === '1') {
				Object.assign(params, {
					alllevel: '1'
				});
			}

			api.getSubordinateInfo(params).then(datas => {
				const {
					status
				} = datas;

				if (status) {
					this.subordinateDataSource = datas.datas;
					resolve();
				} else {
					reject();
				}
			})
		})
	}

	@action showWorkflow = () => {
		this.showToast();
		api.getWorkflowList().then(data => {
			let buttons = [],
				workflowList = data.result;
			workflowList.map(d => {
				buttons.push({
					content: d.title,
					source: d,
					onClick: () => {
						forwardViewForm({
							iscreate: "1",
							workflowid: d.wfid
						});
					}
				});
			});
			buttons.push({
				content: getLabel(32694, '取消'),
			});
			this.showActionSheetWithOptions({
				message: getLabel('500509', '请选择你需要提交的流程'),
				buttons
			});
			this.hideToast();
		})

	}

	@action showActionSheetWithOptions = params => {
		const {
			message,
			buttons: options
		} = params;
		ActionSheet.showActionSheetWithOptions({
			message,
			options,
			cancelButtonIndex: options.length - 1,
			'data-seed': 'logId',
			wrapProps
		});
	}

	@action handleDatePickerChange = (date) => {
		this.date = date;
		// this.date = this.processDate(date);

		this.loadMyAttendanceInfo();
	}

	processDate = (date) => {
		const arr = date.split('-');

		if (parseInt(arr[1]) < 10) {
			return `${arr[0]}-0${arr[1]}`;
		} else {
			return date;
		}
	}

	handleTabClick = (tab, key) => {
		if (key === 0) {
			this.init();
			this.setHrmId(""); //查看下属考勤信息返回后，需要重置hrmId，重新计算layout的route值。
		} else {
			this.getSubordinate();
		};
		this.changeTitle(tab.title);
	}

	getSubordinate = () => {
		this.resetSubordinateDatas();
		this.showToast();
		this.getSubordinateCondition().then(() => {
			this.getSubordinateInfo().then(() => {
				this.hideToast();
			});
		})
	}

	@action resetMyattendanceDatas = () => {
		this.date = moment().format("YYYY-MM");
	}

	@action resetSubordinateDatas = () => {
		this.searchBarValue = '';
		this.alllevel = '0';
	}

	@action resetKqDetail = () => {
		this.isLoadAllDatas = false;
	}

	handleScheduleSelect = (date) => {
		//在日历上点击"今天"时，当前函数会被调用两次。
		this.showToast();
		this.getSignInfo(date).then(() => {
			this.hideToast();
		});
	}

	setPopoverVisible = (visible) => {
		this.popoverVisible = visible;
	}

	onPopoverSelect = () => {
		this.setPopoverVisible(false);
		this.alllevel = (this.alllevel === '0') ? '1' : '0';
		this.loadSubordinateInfo();
	}

	getAdvancedSearchFormParams = (instance) => {
		const {
			dataToParams,
			formData
		} = this[instance].form;

		return dataToParams(formData);
	}

	handleSearchAdvancedSubmit = () => {
		this.searchBarValue = this.getAdvancedSearchFormParams("subordinateSearch")["lastname"];
		this.loadSubordinateInfo();
	}

	handleSearchBarChange = (val) => {
		this.searchBarValue = val;
		this.subordinateSearch.form.updateField("lastname", val);
	}

	handleSearchBarSubmit = () => {
		this.loadSubordinateInfo();
	}

	handleFirstBarPress = () => {
		this.selectedTab = "firstTab";
		this.changeTitle(getLabel(513098, "考勤打卡"));
	}

	handleSecondBarPress = () => {
		this.selectedTab = "secondTab";
	}

	handleBarPress = v => {
		this.selectedTab = v;
		switch(v){
			case 'firstTab':
				this.changeTitle(getLabel(513098, "考勤打卡"));
				break;
			case 'secondTab':
				this.changeTitle(getLabel(513095,"我的考勤"));
				break;
			case 'setting':
				this.changeTitle(getLabel('30747','设置'));
				break;
		}
	}

	openWorkflow = (id) => {
		if (window.em && window.em.checkJsApi && window.em.checkJsApi('openLink')) {
			window.em.openLink({
				url: `/spa/workflow/static4mobileform/index.html#/req?requestid=${id}`,
				openType: 2,
				sysId: window.localStorage.emobile_ec_id
			});
		}else {
			window.location.replace(`/spa/workflow/static4mobileform/index.html#/req?requestid=${id}`)
		}
	}

	changeTitle = (title) => {
		if (window.em && window.em.checkJsApi && window.em.checkJsApi("changeTitle")) {
			window.em.changeTitle({
				title,
				fail: error => Bubble.error(error)
			});
		}else{
			document.title = title;
		}
	}

	setHrmId = (id) => {
		this.hrmId = id;
	}

	setResourceName = (name) => {
		this.resourceName = name;
	}

	setKqType = (type) => {
		this.kqtype = type;
	}

	showToast = () => {
		Toast.loading('', 0);
	}

	hideToast = () => {
		Toast.hide();
		//解决loading多个toast后，toast hide不掉的问题。
		const toasts = document.getElementsByClassName("am-toast");
		if (toasts.length > 0) {
			for (let i = 0; i < toasts.length; i++) {
				toasts[i].remove();
			}
		}
	}

	redirect = (params) => {
		const {
			tabBar,
			page,
			type,
		} = params;

		if (tabBar === "sign") {
			this.handleFirstBarPress();
		}
		if (tabBar === "info") {
			this.handleSecondBarPress();

			this.initialPage = page;

			this.handleTabClick([],parseInt(page));
		}
		this.isOnlyAttendance = (type === "1");
		this.isOnlyAttendance && (this.initialPage = 0);
		
	}

	@observable showSetting = false;
	@action callSignSetting = async () => {
		const data = await getAutoEMSet();
        if(data.status == 1){
            this.showSetting = data.can_set == 1;
        }else{
            Bubble.error(data.message);
        }
	}

	@computed get tabBarItems(){
		const showSetting = this.showSetting;
		const items = [
			{
				title: getLabel(513098,"考勤打卡"),
				key: 'sign',
				icon: <Icon type={'position-o'}/>,
				selectedIcon: <Icon type={'position'} />,
				selected: this.selectedTab === 'firstTab',
				onPress: () => this.handleBarPress('firstTab'),
				['data-seed']: 'sign'
			},{
				title: getLabel(513095,"我的考勤"),
				key: 'attendance',
				icon: <Icon type={'attendance-punch-record'}/>,
				selectedIcon: <Icon type={'attendance'} />,
				selected: this.selectedTab === 'secondTab',
				onPress: () => this.handleBarPress('secondTab'),
				['data-seed']: 'attendance'
			},
		]
		showSetting && items.push({
			title: getLabel('30747','设置'),
			key: 'setting',
			icon: <Icon type={'setting-up'}/>,
			selectedIcon: <Icon type={'setup'} />,
			selected: this.selectedTab === 'setting',
			onPress: () => this.handleBarPress('setting'),
			['data-seed']: 'setting'
		})
		return items;
	}
}

export const myAttendanceCopyStore = new MyAttendanceCopyStore();